<template>
  <el-tabs v-model="activeName">
    <el-tab-pane name="first">
        <template #label>
            <span>
            <el-icon><Setting /></el-icon>
            <span>表属性设置</span>
            </span>
        </template>
		  <el-card>
            <template #header>
                <div class="card-header">
                    <el-button-group>
                        <el-button type="info" :icon="Download" @click="handleExportToJson">导出到JSON</el-button>
                        <el-button :icon="Upload" @click="handleImportJson">导入JSON</el-button>
                        <el-button :icon="Download" @click="handleAllExportToJson" title="一键导出表格属性、数据列、测试数据等全部数据">导出全部到JSON</el-button>
                        <el-button :icon="Upload" @click="handleAllImportJson" title="一键导入表格属性、数据列、测试数据等全部数据">导入全部从JSON</el-button>
                    </el-button-group>
                    
                </div>
            </template>
        <el-form :inline="true" :model="localTableOptions">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="数据接口">
                        <el-input v-model="localTableOptions.dataApi" placeholder="dataApi" clearable  class="custom-width"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="行Key">
                        <el-input v-model="localTableOptions.rowKey" placeholder="rowKey" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="行列布局方式">
                        <el-radio-group v-model="localTableOptions.tableLayout">
                        <el-radio value="fixed">fixed</el-radio>
                        <el-radio value="auto">auto</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="选择类型">
                        <el-radio-group v-model="localTableOptions.selectionType">
                        <el-radio value="none">none</el-radio>
                        <el-radio value="multiple">multiple</el-radio>
                        <el-radio value="single">single</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
				        <el-col :span="12">
                    <el-form-item label="显示默认添加按钮">
                        <el-switch v-model="localTableOptions.showDefaultAdd" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示导出按钮">
                        <el-switch v-model="localTableOptions.showExport" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示导入按钮">
                        <el-switch v-model="localTableOptions.showImport" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示刷新表格按钮">
                        <el-switch v-model="localTableOptions.showRefresh" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示高级搜索按钮">
                        <el-switch v-model="localTableOptions.showAdvancedSearch" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示数据列按钮">
                        <el-switch v-model="localTableOptions.showColumns" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示分页">
                        <el-switch v-model="localTableOptions.pagination" />
                    </el-form-item>
                </el-col>
                            
                <el-col :span="12">
                    <el-form-item label="显示合计行">
                        <el-switch v-model="localTableOptions.showSummary" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="合计列">
                        <el-input-tag v-model="localTableOptions.summaryColumns"  
                            tag-type="primary"
                            tag-effect="plain"  
                            clearable placeholder="summaryColumns" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="默认选中行Keys">
                        <el-input-tag v-model="localTableOptions.selectedRowKeys"
                            tag-type="primary"
                            tag-effect="plain"  
                            clearable placeholder="selectedRowKeys" />
                    </el-form-item>
                </el-col>
				 <el-col :span="12">
                    <el-form-item label="树形配置">
                            <el-button 
                                :type="!isEmpty(localTableOptions.treeProps) ? 'primary' : ''"
                                plain round  :icon="Edit" 
                                @click="showTreePropsOptionsDialog(localTableOptions.treeProps)">treeProps</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="其他属性">
                            <el-button :type="!isEmpty(localTableOptions.options) ? 'primary' : ''" plain round  :icon="Edit" @click="showOtherOptionsDialog(localTableOptions.options)">options</el-button>
                    </el-form-item>
                </el-col>
            </el-row>              
        </el-form>
		</el-card>
    </el-tab-pane>
    <el-tab-pane name="second">
        <template #label>
            <span>
            <el-icon><ScaleToOriginal /></el-icon>
            <span>数据列设置</span>
            </span>
        </template>
        <gtableColumnsEditor :key="'columns' + key"
            v-model:table-columns="localTableColumns"
            v-model:table-data="localTableData"
        />
    </el-tab-pane>
    <el-tab-pane label="" name="third">
        <template #label>
            <span>
            <el-icon><View /></el-icon>
            <span>预览</span>
            </span>
        </template>
 
        
     <gtable :key="'table' + key"
            ref="gtablePreviewRef"
            v-model:table-options="localTableOptions"
            v-model:table-columns="localTableColumns"
            v-model:table-data="localTableData" 
            @handleAdd="handleAdd"
        >
            <template #action="{ row, $index }">
                <el-button-group>
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    <el-button size="small" @click="handleCopy(row)">复制</el-button>
                </el-button-group>      
            </template>
            <template #toolbar>
            </template>
        </gtable>
     
 
    </el-tab-pane>
  </el-tabs>

  <div v-if="showOtherOptionsDialogFlag" v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
		<el-dialog title="其他属性设置" 
							v-model="showOtherOptionsDialogFlag"
								:show-close="true" 
								class="drag-dialog small-padding-dialog" 
								append-to-body
								:close-on-click-modal="false" 
								:close-on-press-escape="false" 
								:destroy-on-close="true">
			<el-form label-width="auto" >				
				<el-form-item label="选项">
					<SearchSelectOptionsInput v-model:options="otherOptions"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="default" type="primary" @click="saveOtherOptions">确定</el-button>
				<el-button size="default" @click="showOtherOptionsDialogFlag = false">取消</el-button>
			</div>
		</el-dialog>
	</div>
	 <div v-if="showTreePropsOptionsDialogFlag" v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
    <el-dialog title="其他属性设置" 
                        v-model="showTreePropsOptionsDialogFlag"
                            :show-close="true" 
                            class="drag-dialog small-padding-dialog" 
                            append-to-body
                            :close-on-click-modal="false" 
                            :close-on-press-escape="false" 
                            :destroy-on-close="true">
        <el-form label-width="auto" >				
            <el-form-item label="选项">
                <SearchSelectOptionsInput v-model:options="treePropsOptions"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="default" type="primary" @click="saveTreePropsOptions">确定</el-button>
            <el-button size="default" @click="showTreePropsOptionsDialogFlag = false">取消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue'
import gtable from '@/components/g-table.vue'
import gtableColumnsEditor from '@/components/g-table-columns-editor.vue'
import SearchSelectOptionsInput from "@/components/search-select-options-input.vue"
import { ElMessage } from 'element-plus'
import { Setting, ScaleToOriginal, View, Edit, Download, Upload } from '@element-plus/icons-vue'
import { isEmpty, deepClone, parseValue } from '@/utils/utils'
import { exportToJson } from '@/utils/export'
import { importFromJson } from '@/utils/import'

const activeName = ref('first')

const props = defineProps({
  tableOptions: { 
    type: Object, 
    default: () => ({}) 
  },
  tableColumns: { 
    type: Array,
    required: true, 
    default: () => []
  },
  tableData: { type: Array, default: () => [] },
  key: { type: String, default: '' }
})

const localTableColumns = ref(props.tableColumns)
const localTableOptions = ref(props.tableOptions)
const localTableData = ref(props.tableData)

const emit = defineEmits([
  'update:tableColumns',
  'update:tableOptions',
  'update:tableData'
])

const otherOptions=ref(localTableOptions.value.options)
const treePropsOptions = ref(localTableOptions.value.treeProps || { 
      children: 'children', // 子级字段名
      hasChildren: 'hasChildren', // 是否有子级字段名（可选）
      checkStrictly: false, // 是否父子不关联
    })
const gtablePreviewRef = ref()

const showOtherOptionsDialogFlag=ref(false)
const showTreePropsOptionsDialogFlag=ref(false)

// 事件
const handleAdd = () => {
  ElMessage.success('新增')
}
const handleEdit = (row) => {
  ElMessage.info('编辑：' + JSON.stringify(row))
}
const handleDelete = (row) => {
  ElMessage.error('删除：' + JSON.stringify(row))
}
const handleCopy = (row) => {
  ElMessage.warning('复制：' + JSON.stringify(row))
}
const handleExportToJson = () => {
    exportToJson(getTableOptions());
}
const handleAllExportToJson = () => {
    exportToJson({
        tableOptions: deepClone(getTableOptions()),
        tableColumns: deepClone(getTableColumns()),
        tableData: deepClone(getTableData())
    }) 
}
const handleImportJson = async () => {
    try {
        const jsonData = await importFromJson();
        if(jsonData){
            setTableOptions(jsonData.tableOptions || jsonData);
        }
           
        ElMessage.success('导入成功')
    } catch (error) {
        console.error('导入失败:', error.message)
    } 
}

const handleAllImportJson = async () => {
    try {
        const jsonData = await importFromJson();
        if(jsonData){
            const { tableOptions, tableColumns, tableData } = jsonData;
             tableOptions && setTableOptions(tableOptions);
            tableColumns && setTableColumns(tableColumns);
            tableData && setTableData(tableData) && refreshTable(); 
        }           
        ElMessage.success('导入成功')
    } catch (error) {
        console.error('导入失败:', error.message)
    } 
}

const showOtherOptionsDialog = (options) => {
  otherOptions.value = Object.keys(options || {}).map(key => ({
    label: key,
    value: options[key] //&& Array.isArray(options[key]) ? options[key].join(',') : options[key]
  }));
  
  showOtherOptionsDialogFlag.value = true;
};
//保存其他表属性
const saveOtherOptions=()=>{
    //console.log(otherOptions.value,isEmpty(otherOptions.value))    
    if(isEmpty(otherOptions.value)){
         localTableOptions.options={}
    }else{
        const retOptions = {}
        otherOptions.value.forEach((item) => {
            if(item.label){
                const val =item.value
                if(item.label==='pageSizes'){
                    retOptions[item.label] = isEmpty(val) ? undefined : val;
                }else{
                    retOptions[item.label] = parseValue(val);
                }  
            }             
        })
        localTableOptions.options=retOptions
    }
   // console.log('保存其他表属性',props.tableOptions.options)   
    showOtherOptionsDialogFlag.value=false
    //ElMessage.success('保存成功')
}

const showTreePropsOptionsDialog = (options) => {
  treePropsOptions.value = Object.keys(options || {}).map(key => ({
    label: key,
    value: options[key]
  }));
  
  showTreePropsOptionsDialogFlag.value = true;
};
//保存其他表属性
const saveTreePropsOptions = (options) => {

    if(isEmpty(treePropsOptions.value)){
         localTableOptions.treeProps={}
    }else{
        const retOptions = {}
        treePropsOptions.value.forEach((item) => {
            if(item.label){
                retOptions[item.label] = parseValue(item.value);
            }             
        })
        localTableOptions.treeProps=retOptions
    }
  showTreePropsOptionsDialogFlag.value = false
}

const refreshTable = () => {
  gtablePreviewRef.value.refreshTable();
}
const setTableColumns = (columns) => {
  localTableColumns.value = columns
}
const setTableOptions = (options) => {
  localTableOptions.value = options
}
const setTableData = (data) => {
  localTableData.value = data
}

const getTableColumns = () => {
  return localTableColumns.value
}
const getTableOptions = () => {
  return localTableOptions.value
}
const getTableData = () => {
  return localTableData.value
}
//暴露方法可进行手动同步或调用
defineExpose({
	setTableColumns,
    setTableOptions,
	setTableData,
	getTableColumns,
    getTableOptions,
	getTableData,
})
watch(
  () => props.tableColumns, (newVal) => {
    localTableColumns.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => props.tableData, (newVal) => {
    localTableData.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => props.tableOptions, (newVal) => {
    localTableOptions.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => localTableColumns, (newVal) => {
    emit('update:tableColumns',localTableColumns.value)
    nextTick(()=>{
      refreshTable();
    })
  },{ deep: true, immediate: true }
)
watch(
  () => localTableData, (newVal) => {
    emit('update:tableData',localTableData.value)
  },{ deep: true, immediate: true }
)
watch(
  () => localTableOptions, (newVal) => {
    emit('update:tableOptions', localTableOptions.value)
  },{ deep: true, immediate: true }
)
</script>

<style scoped> 
.dialog-footer{
	text-align: right;
}
.custom-width {
  width: 450px;
}
/* 或者响应式宽度 */
@media (max-width: 768px) {
  .custom-width {
    width: 50%;
  }
}
</style>